<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/26 0026
 * Time: 22:21
 */
class Worker
{

    protected $socket;

    public $connect;

    public $message;

    public function __construct($socket_address)
    {
        $this->socket = stream_socket_server($socket_address);
    }

    public function accept()
    {
        //第一个需要监听的时间（服务端socket的事件）一旦监听到事件会触发
        swoole_event_add($this->socket, function ($fd) {
            $clientSocket = stream_socket_accept($fd);
            //出发连接事件回调
            if ($clientSocket && is_callable($this->connect)) {
                call_user_func_array($this->connect, array($fd, '触发连接'));
            }
            //监听客户端可读
            swoole_event_add($clientSocket, function ($fd) {
                $clientData = fread($fd, 65535);
                if (!empty($clientData) && is_callable($this->message)) {
                    call_user_func_array($this->message, array($fd, '触发消息事件'));
                }
                fclose($fd);
            });

        });
    }

    public function fork()
    {

        $this->accept();
    }

    public function start()
    {
        $this->fork();

    }

}

$worker = new Worker('tcp://0.0.0.0:9501');

$worker->connect = function ($client, $args) {
    var_dump($client, $args);
};
$worker->message = function ($client, $args) {

};
$worker->start();